// @ts-nocheck
/*
 * @Descripttion: 胡腾辉 | feico
 * @version: V1.0
 * @Author: feico
 * @Date: 2022-02-20 18:01:07
 * @LastEditors: feico
 * @LastEditTime: 2022-02-23 17:18:01
 */
import React, { useEffect,useRef,useState } from 'react'
import styles from './index.module.scss'
import { Breadcrumb, Card,Form,Input,Space,Button,Radio,Upload, message,Modal } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import {Link,useHistory} from 'react-router-dom'
import { useDispatch} from 'react-redux'
import { getChannel,addArticle,getArticleById,editArticle} from '../../store/action/article'
import Channel from '../../components/Channel'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useParams } from 'react-router-dom'

export default function Publish() {
    const dispatch = useDispatch()
    const history = useHistory()
    useEffect(()=>{
        dispatch(getChannel())
    },[dispatch])
    // 发布文章
    const onFinish =async (value)=>{
        console.log(value);
        addContent(value,false)
    }
    // 封装抽取发起添加方法
    const addContent =async(values,draftStatus)=>{
        const images = fileList.map((item)=>{
            if(item.url){
                return item.url
            }else{
                return item.response.data.url
            }
        })
        const {type,...rest} = values
        const params = {
            ...rest,
            cover:{
                type,
                images
            }
        }
        if(id) {
            // 修改
            await dispatch(editArticle({...params,id},draftStatus))
            message.success('修改成功')
        }else{
            await dispatch(addArticle(params,draftStatus))
        }
        message.success('添加成功')
        history.push('/home/article')
    }
    const [fileList,setFileList] = useState([
        {
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
        },
    ])
    const [type, setType] = useState(1)
    const fileRef = useRef(fileList)
    const formRef = useRef(null)
    const onUploadChange=({fileList})=>{
        setFileList(fileList)
        fileRef.current=fileList
        formRef.current.validateFields(['type'])
    }
    const onTypeChange=(e)=>{
        const count=e.target.value 
        setType(count)
        setFileList(fileRef.current.slice(0,count))
    }
    // 存为草稿
    const addDraft=async()=>{
      const values =await formRef.current.validateFields()
      console.log(values);
      addContent(values,true)
    }
    const [isVisible, setIsVisible] = useState(false)
    const [preview, setPreview] = useState('')
    const onPreview = (file) => {
        setIsVisible(true)
        setPreview(file.url || file.response.data.url)
    }
    const { id } = useParams()
        // 根据id数据回显
        useEffect(()=>{
            if(!id) return
            dispatch(getArticleById(id)).then(res=>{
                formRef.current.setFieldsValue({
                    ...res,
                    type:res.cover.type
                })
                setType(res.cover.type)
                const list =res.cover.images.map(item=>({
                    url:item
                }))
                setFileList(list)
                fileRef.current = list
            })
        },[id,dispatch])
        return (
       <div className={styles.root}>
           <Card title={
               <Breadcrumb separator='>'>
                   <Breadcrumb.Item>
                   <Link to='/home'>首页</Link>
                   </Breadcrumb.Item>  
                   <Breadcrumb.Item>{id ? '编辑' : '发布'}文章</Breadcrumb.Item>  
               </Breadcrumb>
           }>
               <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} size='large' initialValues={{content:'',type:1}} onFinish={onFinish} validateTrigger={['onBlur','onChange']} ref={formRef}>
                <Form.Item label='标题' name='title' rules={[
                   {required:true,
                    message:'标题不能为空'}
                ]}>
                    <Input placeholder='请输入文章的标题' style={{ width: 400 }} />
                </Form.Item>
                {/* 频道 */}
                <Form.Item label='频道' name='channel_id' rules={[
                    {
                        required:true,
                        message:'频道不能为空'
                    }
                ]}>
                        <Channel/>
                    </Form.Item>
                    <Form.Item label='封面' name='type' rules={[
                        {
                            validator(_,value){
                                if(fileList.length!== value){
                                    return Promise.reject(new Error(`请上传${value}张图片`))
                                }else{
                                    return Promise.resolve()
                                }
                            }
                        }
                    ]}>
                        <Radio.Group onChange={onTypeChange}>
                            <Radio value={1}>单图</Radio>
                            <Radio value={3}>三图</Radio>
                            <Radio value={0}>无图</Radio>
                        </Radio.Group>
                        </Form.Item>
                        {type>0 && (
                            <Form.Item wrapperCol={{offset:4}}>
                            <Upload listType='picture-card' fileList={fileList} action={`${process.env.REACT_APP_URL}upload`} name='image' onChange={onUploadChange} maxCount={type} onPreview={onPreview}>
                               {fileList.length<type &&  <PlusOutlined />}
                            </Upload>
                        </Form.Item>
                        )}
                <Form.Item label='内容' name='content' rules={[
                    {
                        required:true,
                        message:'内容不能为空'
                    }
                ]}>
                    <ReactQuill/>
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
                    <Space>
                        <Button type='primary' htmlType='submit'>{id ? '编辑' : '发布'}文章</Button>
                        <Button onClick={addDraft}>存入草稿</Button>
                    </Space>
                </Form.Item>
            </Form>
            <Modal width={800} title='图片预览' visible={isVisible} footer={null} onCancel={() => setIsVisible(false)}>
                <div style={{ textAlign: 'center' }}>
                    <img src={preview} style={{width:600}} alt="" />
                </div>
            </Modal>
           </Card>
       </div>
            )
    }